package com.example.dormmanage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.dormmanage.dao.IAdminDao;
import com.example.dormmanage.dao.IStudentDao;
import com.example.dormmanage.entity.Admin;
import com.example.dormmanage.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.TreeSet;

/**
 * 实现UserDetail抽象方法,封装UserDetail对象
 */
@Service
public class UserDetailImpl implements UserDetailsService {

    @Autowired
    private IStudentDao studentDao;

    @Autowired
    private IAdminDao adminDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //判断用户身份,区分管理员和普通学生
        if (username.split("@")[1].equals("admin")) {//管理员登录
            LambdaQueryWrapper<Admin> lqw = new LambdaQueryWrapper<>();
            lqw.eq(Admin::getUserName, username.split("@")[0]);
            Admin selectAdmin = adminDao.selectOne(lqw);
            if (Objects.isNull(selectAdmin)) {
                throw new UsernameNotFoundException("用户名或密码错误");
            }
            // TODO 根据用户查询权限信息 添加到LoginUser中
            List<String> listMenu = adminDao.selectUserMenuList(selectAdmin.getRoleId());//获取用户权限列表
            return new LoginUser(selectAdmin,listMenu);
        }
        //根据用户名查询用户信息
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Student::getUserName, username.split("@")[0]);
        Student selectStudent = studentDao.selectOne(wrapper);
        //如果查询不到数据就通过抛出异常来给出提示
        if (Objects.isNull(selectStudent)) {
            throw new RuntimeException("用户名或密码错误");
        }
        //TODO 根据用户查询权限信息 添加到LoginUser中
        List<String> listMenu = studentDao.selectUserMenuList(selectStudent.getRoleId());//获取学生的权限列表
        //封装成UserDetails对象返回
        return new LoginUser(selectStudent,listMenu);

    }
}
